﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Slwy.FrameCore.Dependency;
using System;
using System.Collections.Generic;
using Slwy.EventBus.Models;
using Slwy.FrameCore.Extension;
using Slwy.FrameCore.Helper;
using Slwy.Logger.Contracts;
using Slwy.Utility.ConfigurManager;
using Slwy.Utility.Extensions;

namespace Slwy.EventBus
{
    public static class EventBusApplicationBuilderExtensions
    {
        /// <summary>
        /// 注册事件总线服务
        /// </summary>
        /// <param name="app"></param>
        public static void UseEventBus(this IApplicationBuilder app)
        {
            var logger = ServiceLocator.Instance.GetService<ILogger>();
            var httpClient = ServiceLocator.Instance.GetServiceEx<ISlwyHttpClient>();
            var subscribes = new ConfigurHandler().GetAppOptions<List<MSubscribe>>("EventBus");

            foreach (var subscribe in subscribes)
            {
                try
                {
                    var result = httpClient.Post<bool>("/api/eventbus/Event/subscriber", subscribe);
                    if (result)
                    {
                        logger.Info($"事件注册成功: {subscribe.RoutingKey}  {subscribe.QueueName}  {subscribe.CallBackUrl}");
                    }
                    else
                    {
                        logger.Error($"事件注册失败(eventbus-service 调用成功,但是注册失败): {subscribe.RoutingKey}  {subscribe.QueueName}  {subscribe.CallBackUrl}");
                    }
                }
                catch (Exception e)
                {
                    logger.Error(e, $"事件注册失败(eventbus-service 调用失败): {subscribe.RoutingKey}  {subscribe.QueueName}  {subscribe.CallBackUrl}");
                }
            }
        }
    }
}

